package com.tma.demolocalservice;
import android.app.Service;
import android.content.Intent;
import android.os.Bundle;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.util.Log;
import android.widget.Toast;


public class MyLocalService extends Service {
    private static final String TAG = "MyLocalService";
    private ThreadGroup mThreadGroup;
    private Messenger mOutMessenger;

    @Override
    public void onCreate() {
        super.onCreate();

        Log.i(TAG, "Service: onCreate");
        Toast.makeText(this, "Service: onCreate", Toast.LENGTH_SHORT).show();

        // Initialize service here
        mThreadGroup = new ThreadGroup("MyLocalServiceWorkers");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

        Log.i(TAG, "Service: onDestroy");
        Toast.makeText(this, "Service: onDestroy", Toast.LENGTH_SHORT).show();

        // Do clean up
        mThreadGroup.interrupt();
    }

    @Override
    public IBinder onBind(Intent intent) {
        // Local service should return null
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.i(TAG, "Service: onStartCommand");
        Toast.makeText(this, "Service: onStartCommand", Toast.LENGTH_SHORT).show();

        // TODO Use additional threads to do in background 
        handleCommand(intent);
        return Service.START_STICKY;
    }

    private void handleCommand(Intent intent) {
        if (intent == null) {
            return;
        }
        
        if (intent.hasExtra(I.KEY_MESSENGER)) {
            mOutMessenger = intent.getParcelableExtra(I.KEY_MESSENGER);
        }
        Thread worker = new Thread(mThreadGroup, new Worker());
        worker.start();
    }

    private void reportStatus(String status) {
        if (mOutMessenger != null) {
            Message msg = Message.obtain();
            Bundle b = new Bundle();
            b.putString(I.KEY_STATUS, status);
            msg.setData(b);
            try {
                mOutMessenger.send(msg);
            } catch (RemoteException e) {
                Log.e(TAG, e.getMessage(), e);
            }
        }
    }

    class Worker implements Runnable {
        @Override
        public void run() {
            for (int i = 1; i <= 100; i++) {
                String status = "Processing: " + i + " / " + 100;
                Log.i(TAG, status);
                reportStatus(status);
                try {
                    Thread.sleep(50);
                } catch (InterruptedException e) {
                    Log.e(TAG, e.getMessage(), e);
                }
            }
            reportStatus("Done");
        }
    }
}
